<template>
	<div>
		<template v-if="editMode">
			<component :is="formComponent" ref="form" :model="model" v-model="currentDataRow" @cancel="onCancel" :id="currentId" :params-data="paramsData" @saved="onSaved"></component>
		</template>
		<template v-else >
			<el-button style="margin-bottom: 10px" v-if="allowAdd" type="primary" @click="onAdd" icon="plus">添加</el-button>
			<wt-paged-table
					v-loading="deleting || getting"
					ref="pager"
					:url="query.url"
					:transfer="query.transfer"
					:url-method="query.method"
					:initial-page="0"
					:total-size="totalSize"
					:page-size="pageSize"
					:page-param="pageParam"
					:extra-params="extraParams"
					:result-param="model.tableName"
					@page-loaded="onPageLoaded"
					filter-param=""
					:count-param="query.countParam"
					:size-param="query.sizeParam"
					:show-pagination="showPagination"
					:refresh="shouldRefreshTable">
				<el-table
					:data="currentValue"
					style="width: 100%">
					<el-table-column v-for="(field,index) in fields" :min-width="field.minWidth" v-if="field.display" :key="index" :label="field.label" :prop="field.tableName" >
						<template scope="scope">
							<template v-if="field.customDisplayComponent">
								<component :is="field.customDisplayComponent" :value="scope.row[field.tableName]" :field="field"></component>
							</template>
							<template v-else-if="field.type === types.images">
								<wt-images :value="scope.row[field.tableName]">field</wt-images>
							</template>
							<template v-else>
								{{ format(scope.row, field) }}
							</template>
						</template>
					</el-table-column>
					<slot></slot>
					<el-table-column
							v-if="allowEdit || allowRemove"
							label="操作"
							:min-width="minHandleWidth">
						<template scope="scope">
							<el-button v-if="allowEdit" @click="edit(scope.row)" size="small" icon="edit">编辑</el-button>
							<el-button v-if="allowRemove" @click="remove(scope.row,scope.$index)" size="small" icon="delete2">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</wt-paged-table>
		</template>
	</div>
</template>
<script>
	import Vue from 'vue';
	import ElementUI from 'element-ui';
	import Fields from '../utils/wt-model-field';
	import FormUtils from '../utils/wt-form-utils';
	import TimeUtils from '../utils/wt-time-utils';
	import ModelUtils from '../utils/wt-model-utils';
	import Service from '../utils/wt-model-service';
	import PagedTable from './wt-paged-table';
	import request from 'winged/utils/axios';
	import Images from './wt-images';
	import Permission from '../utils/wt-permission';
	import ModelForm from './wt-model-form';

	Vue.use(ElementUI);
	Vue.component(PagedTable.name, PagedTable);
	Vue.component(Images.name, Images);
	Vue.component(ModelForm.name, ModelForm);
	export default {
		name: 'wt-model-table',
		props: {
			model: Object,
			value: {
				type: Array,
				default: null
			},
			// 如果为true，则在组件创建后自动进行数据加载
			autoLoad: {
				type: Boolean,
				default: false
			},
			// 用于组合extraParams的参数集合
			paramsData: {
				type: Object,
				default: null
			},
			pageSize: {
				type: Number,
				default: 10
			},
			initialLoading: {
				type: Boolean,
				default: false
			},
			allowAdd: {
				type: Boolean,
				default: true
			},
			allowEdit: {
				type: Boolean,
				default: true
			},
			allowRemove: {
				type: Boolean,
				default: true
			},
			total:{
				type: Number,
				default: 0
			},
			showPagination: {
				type: Boolean,
				default: true
			},
			minHandleWidth:{
				type:Number,
				default:180
			},
			resultParam:{
				type:String,
				default:''
			},
			pageParam:{
				type:String,
				default:'index'
			},
			isReload:{
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				currentValue: null,
				formatters: [],
				totalSize: this.total,
				extraParams: null,
				editMode: false,
				currentId: null,
				currentDataRow: null,
				shouldRefreshTable: false,
				types: Fields.types,
				deleting: false,
				getting: false,
			}
		},
		watch:{
			value: function(val, old){
				if (val === old) return;
				this.onPageLoaded(val);
			}
		},
		computed: {
			fields: function() {
				return this.model.fields;
			},
			query: function() {
				return this.model.query;
			},
			formComponent: function() {
				return this.model.customFormComponent ? this.model.customFormComponent : 'wt-model-form'
			}
		},
		methods: {
			parseImages(value) {
				if (typeof value === 'string') {
					return JSON.parse(value);
				}
				else {
					return [];
				}
			},
			format(row, field) {
				return ModelUtils.formatFieldDisplay(row, field);
			},
			count() {
				if(!this.model.count) return;
			    let vm = this;
			    let data = {case_id : this.paramsData.case_id};
                request(this.model.count.url,this.model.count.method, data, true, function(data) {
                    vm.totalSize = Number(data);
					vm.$emit('count', { model: vm.model, data: Number(data)});
                }, function(error) {
                    vm.$message.error('获取失败');
                });
			},
			load() {
				this.count()
				// 编辑模式下无法调用load
				if (!this.editMode) {
					this.$nextTick(() => {
						this.$refs.pager.load();
					})
				}
				else {
					this.$refs.form.load();
				}
			},
			onPageLoaded(data) {
				if (data) {
					if (this.model.tableName && !Array.isArray(data) && Object.prototype.toString.call(data) == '[object Object]') {
						data = data[this.model.tableName];
					}
					if (this.model.builder) {
						data = this.model.builder(data);
					}
					for (let i = 0; i < data.length; i ++) {
						ModelUtils.normalizeData(this.model, data[i]);
					}
				}
				this.currentValue = data;
				this.shouldRefreshTable = false;
				this.$emit('table-data',data)
			},
			buildExtraParams() {
				this.extraParams = ModelUtils.buildQueryExtraParams(this.model.query, this.paramsData);
			},
			onAdd() {
				this.currentId = null;
				this.currentDataRow = null;
				this.editMode = true;
			},
			onCancel() {
				this.currentId = null;
				this.currentDataRow = null;
				this.editMode = false;
				//如果列表为空，则重新获取，shouldRefreshTable为true，会自动调用load方法
                if (this.currentValue == null || this.currentValue.length == 0) {
                    this.shouldRefreshTable = true;
                    this.count()
                }

			},
			onSaved(data) {
//				this.shouldRefreshTable = true;
				this.editMode = false;
				if(this.isReload){
					this.load()
				}else{
					let arr = this.value;
					let flag = false
					for(let i = 0; i<this.value.length; i++){
						if(this.value[i].id == data.id){
							flag = true;
							break;
						}else{
							flag = false;
						}
					}
					if(!flag){
						arr.push(data)
					}
					this.value = arr;
				}
				// 无法使用$refs调用，因为table处于v-if块内，而当前处于editMode
			},
			startEdit(data) {
				this.currentDataRow = data;
				this.editMode = true;
			},
			edit(row) {
				this.currentId = ModelUtils.getIdValueFromQueryResult(this.model, row);
				if (this.query.getOnEdit) {
					let _this = this;
					this.getting = true;
					Service.getOne(this.model, this.currentId, function(data) {
						_this.getting = false;
						_this.startEdit(ModelUtils.normalizeData(_this.model, FormUtils.parseObject(data)));
					}, function(error) {
						console.error('[wt-model-table] get record', error);
						_this.getting = false;
						_this.$message.error('查询记录信息失败，请重试');
					});
				}
				else {
					this.startEdit(row);
				}
			},
			remove(row,index) {
				let id = ModelUtils.getIdValueFromQueryResult(this.model, row);
				let vm = this;
				this.$confirm('您将删除该'+ this.model.title +'，是否确定？','操作提示',{
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.deleting = true;
					Service.remove(this.model, id, function(data){
						vm.deleting = false;
						vm.load();
					}, function(error) {
						vm.deleting = false;
						vm.$message.error('删除失败');
					});
				}).catch(() => {
					vm.deleting = false;
				})

			},
		},
		created() {
			this.buildExtraParams()
			this.onPageLoaded(this.value);
		},
		mounted() {
			if (this.autoLoad) {
				if (this.currentValue == null || this.currentValue.length == 0) {
					this.load();
				}
			}
		}
	}
</script>